package pkg

import (
	"sync"
	"system-admin/internal/app/web/service/area"
	"system-admin/internal/define"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/go-cache"
)

// 为加快数据加载速度，做的数据缓存，会定时更新

var _areaTree *areaTree

type areaTree struct {
	once sync.Once
}

// 实例化areaTree
func NewAreaTree() *areaTree {
	if _areaTree == nil {
		_areaTree = &areaTree{}
		_areaTree.once.Do(func() {
			go func() {
				tk := time.NewTicker(time.Duration(time.Hour))
				for {
					<-tk.C
					_areaTree.Refresh()
				}
			}()
		})
	}
	return _areaTree
}

// AreaTree 刷新
func (*areaTree) Refresh() {
	tree1, _ := area.AllTree(1)
	cache.Set(define.CacheAreaTreeLevel1, tree1, 0, nil)

	tree2, _ := area.AllTree(2)
	cache.Set(define.CacheAreaTreeLevel2, tree2, 0, nil)

	tree3, _ := area.AllTree(3)
	cache.Set(define.CacheAreaTreeLevel3, tree3, 0, nil)
}

// AreaTree 获取
func (*areaTree) Get(level int) (interface{}, error) {
	key := define.CacheAreaTreeLevel3
	if level == 1 {
		key = define.CacheAreaTreeLevel1
	} else if level == 2 {
		key = define.CacheAreaTreeLevel2
	}

	val, found := cache.Get(key)
	if found {
		return val, nil
	}
	return []map[string]interface{}{}, errorx.New("区域列表获取失败", -1)
}
